#!/bin/sh

. /usr/share/libubox/jshn.sh

ApCliEnable=$(uci -q get repeater.@main[0].ApCliEnable)
ApCliSsid=$(uci -q get repeater.@main[0].ApCliSsid)
ApCliWPAPSK=$(uci -q get repeater.@main[0].ApCliWPAPSK)

uci set wireless.@wifi-iface[0].ApCliEnable=$ApCliEnable
uci set wireless.@wifi-iface[0].ApCliSsid=$ApCliSsid
uci set wireless.@wifi-iface[0].ApCliWPAPSK=$ApCliWPAPSK

if [ "$ApCliEnable" != "1" ];
then
	uci set wireless.@wifi-iface[0].MACRepeaterEn=
	uci set wireless.@wifi-iface[1].disabled=1
	uci commit wireless
	ifconfig apcli0 down
	brctl delif br-lan apcli0
	exit 0
fi

uci set wireless.@wifi-iface[0].MACRepeaterEn=1

[ ! -f /tmp/ap_scan ] && ap_client -s ra0 -q -o /tmp/ap_scan -j

data=$(cat /tmp/ap_scan)
json_load "$data"
json_get_keys keys list	
json_select list

for key in $keys; do
	json_select $key
	json_get_vars ssid security crypto channel
	
	if [ "$ssid" = "$ApCliSsid" ];then
		[ "$security" = "WPA1PSKWPA2PSK" ] && security=WPAPSKWPA2PSK
		uci set wireless.@wifi-iface[0].ApCliAuthMode=$security
		uci set wireless.@wifi-iface[0].ApCliEncrypType=$crypto
		uci set wireless.mt7628.auotch=0
		uci set wireless.mt7628.channel=$channel
		uci set wireless.@wifi-iface[1].disabled=
		uci commit wireless
		/etc/init.d/network restart
		exit 0
	fi
	
	json_select ..
done